<!--
 * @Author: guandeshen 295570679@qq.com
 * @Date: 2024-08-20 21:20:43
 * @LastEditors: guandeshen 295570679@qq.com
 * @LastEditTime: 2024-09-18 16:45:10
 * @FilePath: /task-admin/src/views/system/role/index.vue
 * @Description: 
 * 
 * Copyright (c) 2024 by RSC, All Rights Reserved. 
-->
<template>
  <div class="container">
    <!-- 列表 -->
    <page-content
      ref="contentRef"
      :stripe="true"
      :content-config="contentConfig"
      @add-click="handleOpenDialog"
      @edit-click="handleOpenDialog"
      @permissions-click="handlePermissionsClick"
    >
      <template #status="scope">
        <el-tag :type="scope.row.status == 'normal' ? 'primary' : 'info'">{{
          scope.row.status == "normal" ? $t("common.show") : $t("common.hide")
        }}</el-tag>
        <!-- <el-switch
          v-model="scope.row.status"
          active-value="normal"
          inactive-value="hidden"
        /> -->
      </template>
    </page-content>

    <!-- 新增表单弹窗 -->
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      width="400px"
      @close="handleCloseDialog"
    >
      <el-form
        ref="roleFormRef"
        :model="formData"
        :rules="rules"
        label-position="top"
      >
        <el-row :gutter="32">
          <el-col :span="24">
            <el-form-item :label="$t('common.roleName')" prop="name">
              <el-input
                v-model="formData.name"
                :placeholder="$t('common.pleaseEnter')"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('common.sort')" prop="weigh">
              <el-input-number v-model="formData.weigh" :min="0" :max="99999" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('common.status')" prop="status">
              <el-switch
                v-model="formData.status"
                active-value="normal"
                inactive-value="hidden"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">{{
            $t("common.save")
          }}</el-button>
          <el-button @click="handleCloseDialog">{{
            $t("common.cancel")
          }}</el-button>
        </div>
      </template>
    </el-dialog>

    <!--权限配置弹窗-->
    <el-drawer
      v-model="drawerDialog.visible"
      :title="drawerDialog.title"
      size="360px"
      @close="handleDrawerCloseDialog"
    >
      <el-input
        class="mb-16px"
        v-model="filterText"
        style="width: 100%"
        placeholder="Filter keyword"
        :suffix-icon="Search"
      />
      <el-tree
        ref="treeRef"
        style="max-width: 600px"
        :data="menuData"
        show-checkbox
        node-key="id"
        :default-checked-keys="formData.rules"
        default-expand-all
        :props="defaultProps"
        :filter-node-method="filterNode"
      />
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleDrawerSubmitClick">{{
            $t("common.save")
          }}</el-button>
          <el-button @click="handleDrawerCloseDialog">{{
            $t("common.cancel")
          }}</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script lang="ts" setup>
import contentConfig from "./config/content";
import type { IObject } from "@/hooks/usePage";
import { RoleForm } from "@/api/role/model";
import { MenuTreeList } from "@/api/menu/model";
import type PageContent from "@/components/PageContent/index.vue";
import RoleAPI from "@/api/role";
import MenuAPI from "@/api/menu";
import { Search } from "@element-plus/icons-vue";

const { t } = useI18n();
// 弹窗
const dialog = reactive({
  title: "",
  visible: false,
});
const formData = reactive<RoleForm>({
  status: "normal",
  weigh: 0,
});
const rules = reactive({
  name: [{ required: true, message: t("common.pleaseEnter"), trigger: "blur" }],
  status: [
    { required: true, message: t("common.pleaseSelect"), trigger: "blur" },
  ],
});
// 新增
function handleOpenDialog(row?: IObject) {
  dialog.visible = true;
  if (row?.id) {
    dialog.title = t("common.modifyRole");
    const { createtime, ...rest } = row;
    Object.assign(formData, rest);
  } else {
    dialog.title = t("common.addRole");
  }
}

/** 关闭弹窗 */
const roleFormRef = ref(ElForm);
function handleCloseDialog() {
  dialog.visible = false;
  roleFormRef.value.resetFields();
  roleFormRef.value.clearValidate();
  formData.id = undefined;
  formData.status = "normal";
  formData.weigh = 0;
}

/** 提交表单 */
const loading = ref(false);
const contentRef = ref<InstanceType<typeof PageContent>>();
function handleSubmit() {
  roleFormRef.value.validate((valid: any) => {
    if (valid) {
      loading.value = true;
      const Id = formData.id;
      RoleAPI.add(formData)
        .then(() => {
          ElMessage.success(
            Id
              ? t("common.modifiedSuccessfully")
              : t("common.newSuccessfullyAdded")
          );
          handleCloseDialog();
          contentRef.value?.fetchPageData({}, true); //重置查询
        })
        .finally(() => {
          loading.value = false;
        });
    }
  });
}

// 权限配置
// 弹窗
const drawerDialog = reactive({
  title: t("common.permissions"),
  visible: false,
});
const defaultProps = {
  children: "childlist",
  label: "title",
};
const menuData = ref<MenuTreeList[]>([]);
/** 关闭弹窗 */
const permissionsFormRef = ref(ElForm);
function handleDrawerCloseDialog() {
  drawerDialog.visible = false;
  filterText.value = "";
  formData.id = undefined;
  formData.rules = [];
  treeRef.value!.setCheckedKeys([]);
}

// 过滤树
const filterText = ref("");
const treeRef = ref<InstanceType<typeof ElTree>>();

watch(filterText, (val) => {
  treeRef.value!.filter(val);
});
interface Tree {
  [key: string]: any;
}
const filterNode = (value: string, data: Tree) => {
  if (!value) return true;
  return data.title ? data.title.includes(value) : true;
};

// 配置权限
const handlePermissionsClick = (row: IObject) => {
  // 设置当前的权限
  Object.assign(formData, row);
  drawerDialog.visible = true;
};
const handleDrawerSubmitClick = () => {
  const checkedKeys = treeRef.value!.getCheckedKeys();
  formData.rules = checkedKeys as string[];
  const { createtime, ...parms } = formData;
  RoleAPI.add(parms).then(() => {
    t("common.modifiedSuccessfully");
    handleDrawerCloseDialog();
    contentRef.value?.fetchPageData({}, true); //重置查询
  });
};

onMounted(() => {
  MenuAPI.getTree({}).then((data) => {
    menuData.value = data;
  });
});
</script>

<style scoped>
/* @import url(); 引入公共css类 */
</style>
